package org.example;

import bean.DB;
import bean.ResponseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/adminKeyVerificationServlet")
public class adminKeyVerificationServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入的管理员密钥
        String adminKey = request.getParameter("adminKey");

        // 如果没有输入密钥，返回错误信息
        if (adminKey == null || adminKey.trim().isEmpty()) {
            ResponseUtils.sendResponse(response, "请输入管理员密钥", "adminKeyPage.jsp");
            return;
        }

        // 创建数据库连接
        DB db = new DB();
        String query = "SELECT adminkey FROM users WHERE adminkey = ?";

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setString(1, adminKey); // 设置查询参数为用户输入的密钥

            ResultSet rs = pstmt.executeQuery();

            // 检查管理员密钥是否为空
            if (!rs.next()) {
                // 如果没有找到任何记录，说明管理员密钥为空
                ResponseUtils.sendResponse(response, "没有获取管理员权限", "managerLogin.jsp");
            } else {
                // 如果查询到了管理员密钥且不为空
                String storedAdminKey = rs.getString("adminkey");
                if (storedAdminKey == null) {
                    // 如果密钥为 null，提示没有权限
                    ResponseUtils.sendResponse(response, "没有获取管理员权限", "managerLogin.jsp");
                } else {
                    // 密钥正确且非空，验证通过
                    ResponseUtils.sendResponse(response, "密钥验证成功，欢迎进入管理员界面", "manager.jsp");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库连接错误，请稍后重试", "managerLogin.jsp");
        }
    }
}
